#include <jni.h>
#include <iostream>
#include <cstdint>
#include <cstring>


// 定义一个结构体，使用固定大小的数据类型
#pragma pack(push, 1) // 禁用对齐
struct Person {
   char name[50];
   std::int64_t id;  // 使用固定大小的int64_t
   std::int32_t age;
   std::int32_t height;
};
#pragma pack(pop) // 恢复对齐

extern "C" {
    JNIEXPORT void JNICALL Java_com_cande_jni_bytetest_ByteTest_readPersonData(JNIEnv *env, jobject obj, jbyteArray data) {
        // 获取字节数组长度
        jsize length = env->GetArrayLength(data);

        // 分配内存并获取字节数组数据
        jbyte *bytes = env->GetByteArrayElements(data, NULL);

        // 创建一个结构体实例并从字节数组中读取数据
        if (length == sizeof(Person)) {
            Person person;
            std::memcpy(&person, bytes, sizeof(person));


            std::cout << "Person size: " << sizeof(Person)<< std::endl;
            std::cout << "Person size: " << sizeof(person)<< std::endl;


            // 打印结构体成员
            std::cout << "Name: " << person.name << std::endl;
            std::cout << "ID: " << person.id << std::endl;
            std::cout << "Age: " << person.age << std::endl;
            std::cout << "Height: " << person.height << std::endl;



        } else {
            std::cerr << "Error: Byte array length does not match Person structure size." << std::endl;
        }

        // 释放内存
        env->ReleaseByteArrayElements(data, bytes, JNI_ABORT);
    }



    JNIEXPORT jbyteArray JNICALL Java_com_cande_jni_bytetest_ByteTest_returnPersonData(JNIEnv *env, jobject obj){
        // 创建一个 byte 数组
        jbyteArray byteArray = env->NewByteArray(sizeof(Person));
        if (byteArray == nullptr) {
            return nullptr; // 内存分配失败
        }

        Person person1;
        std::strcpy(person1.name, "name1");
        person1.id = 1;
        person1.age = 2;

        // 将结构体数据复制到 byte 数组
        env->SetByteArrayRegion(byteArray, 0, 50 + 8 + 4 + 4, reinterpret_cast<const jbyte*>(&person1));
         return byteArray;

    }


    JNIEXPORT jbyteArray JNICALL Java_com_cande_jni_bytetest_ByteTest_testDirectMem (JNIEnv *env, jobject obj, jlong ll){

            char* buffer = (char*)ll;

            for (int i = 0; i < 10; i++) {
                std::cout << static_cast<int>(buffer[i]) << " ";
            }
             std::cout << std::endl;

             return 0;
    }

}